#! -*- coding:utf-8 -*-
import os
import json
import logging
from datetime import datetime, timedelta

from common.stats import MG_BIGBANG_COLL as mg
from common.utils import tz

from django.core.management.base import BaseCommand


_LOGGER = logging.getLogger('worker')


def create_daily_recharge():
    now = tz.local_now()
    day = tz.get_utc_date()
    if now.hour == 0:
        day = day - timedelta(days=1)
    end = day + timedelta(days=1)
    date_str = tz.utc_to_local(day).strftime('%Y-%m-%d')
    index = now.hour - 1 if now.hour>0 else 23
    print 'creating date:%s, index:%s' % (date_str, index)
    value = {
        '_id': '%s-%s' % (date_str, index),
        'day': date_str,
        'index': index,
        'time_start': '%s %d:00' % (date_str, index),
        'time_end': '%s %d:00' % (date_str, index+1),
    }
    t = mg.daily_stats.aggregate([
        {"$match": {"$and": [
            {"updated_at": {"$gte": day, "$lt": end}},
            {"recharge.total": {"$gt": 0}}
        ]}},
        {"$group": {"_id": None, "total": {"$sum": 1},
                    "price": {"$sum": "$recharge.total"}}}
    ])
    t = t.next() if t.alive else {}
    value['recharge_user'] = t.get('total', 0)
    value['recharge_price'] = t.get('price', 0)
    if index > 0:
        last_one = mg.daily_charge_report.find_one({'_id': '%s-%s' % (date_str, index-1)})
        if not last_one:
            delta_price = 0
        else:
            delta_price = value['recharge_price'] - last_one['recharge_price']
    else:
        delta_price = value['recharge_price']
    value['delta_price'] = delta_price
    mg.daily_charge_report.insert_one(value)


class Command(BaseCommand):

    def handle(self, **kwargs):
        create_daily_recharge()
